<template>
  <div class="appointment-container">
    <div class="page-header">
      <h2>预约管理</h2>
      <el-button type="primary" @click="handleTimeSlot">
        时间段设置
      </el-button>
    </div>

    <el-card class="search-card">
      <el-form :inline="true" :model="searchForm" ref="searchFormRef">
        <el-form-item label="访客姓名">
          <el-input v-model="searchForm.visitorName" placeholder="请输入访客姓名"/>
        </el-form-item>
        <el-form-item label="状态">
          <el-select style="width: 100px" v-model="searchForm.status" placeholder="请选择状态">
            <el-option label="全部" value=""/>
            <el-option label="待审核" value="pending"/>
            <el-option label="已确认" value="confirmed"/>
            <el-option label="已取消" value="cancelled"/>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <el-card>
      <el-table
          v-loading="loading"
          :data="tableData"
          style="width: 100%"
      >
        <el-table-column prop="id" label="预约编号" width="120"/>
        <el-table-column prop="visitorName" label="访客姓名"/>
        <el-table-column prop="visitorPhone" label="联系电话"/>
        <el-table-column prop="appointmentDate" label="预约日期" width="120"/>
        <el-table-column prop="timeSlotId" label="时间段" width="160">
          <template #default="{ row }">
            {{ timeSlotMap.get(row.timeSlotId?.toString()) || '未知时间段' }}
          </template>
        </el-table-column>
        <el-table-column prop="visitorCount" label="访客人数" width="100"/>
        <el-table-column prop="status" label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="getStatusType(row.status)">
              {{ getStatusText(row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" width="180"/>
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-button-group>
              <el-button
                  v-if="row.status === 'PENDING'"
                  type="primary"
                  link
                  @click="handleReview(row)"
              >
                审核
              </el-button>
              <el-button type="primary" link @click="handleDetail(row)">
                详情
              </el-button>
            </el-button-group>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination-container">
        <el-pagination
            v-model:current-page="currentPage"
            v-model:page-size="pageSize"
            :page-sizes="[10, 20, 50, 100]"
            :total="total"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 添加审核对话框 -->
    <el-dialog
      v-model="reviewDialogVisible"
      title="预约审核"
      width="500px"
    >
      <el-form :model="reviewForm" label-width="100px">
        <el-form-item label="访客姓名">
          <span>{{ currentRow.visitorName }}</span>
        </el-form-item>
        <el-form-item label="联系电话">
          <span>{{ currentRow.visitorPhone }}</span>
        </el-form-item>
        <el-form-item label="预约日期">
          <span>{{ currentRow.appointmentDate }}</span>
        </el-form-item>
        <el-form-item label="时间段">
          <span>{{ timeSlotMap.get(currentRow.timeSlotId?.toString()) || '未知时间段' }}</span>
        </el-form-item>
        <el-form-item label="访客人数">
          <span>{{ currentRow.visitorCount }} 人</span>
        </el-form-item>
        <el-form-item label="审核结果">
          <el-radio-group v-model="reviewForm.status">
            <el-radio label="CONFIRMED">通过</el-radio>
            <el-radio label="REJECTED">拒绝</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="备注" v-if="reviewForm.status === 'REJECTED'">
          <el-input
            v-model="reviewForm.remark"
            type="textarea"
            rows="3"
            placeholder="请输入拒绝原因"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="reviewDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitReview">
            确定
          </el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 添加详情对话框 -->
    <el-dialog
      v-model="detailDialogVisible"
      title="预约详情"
      width="600px"
    >
      <el-descriptions :column="2" border>
        <el-descriptions-item label="预约编号">{{ detailData.id }}</el-descriptions-item>
        <el-descriptions-item label="访客姓名">{{ detailData.visitorName }}</el-descriptions-item>
        <el-descriptions-item label="联系电话">{{ detailData.visitorPhone }}</el-descriptions-item>
        <el-descriptions-item label="预约日期">{{ detailData.appointmentDate }}</el-descriptions-item>
        <el-descriptions-item label="时间段">
          {{ timeSlotMap.get(detailData.timeSlotId?.toString()) || '未知时间段' }}
        </el-descriptions-item>
        <el-descriptions-item label="访客人数">{{ detailData.visitorCount }}</el-descriptions-item>
        <el-descriptions-item label="状态">
          <el-tag :type="getStatusType(detailData.status)">
            {{ getStatusText(detailData.status) }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="创建时间">{{ detailData.createTime }}</el-descriptions-item>
        <el-descriptions-item label="备注" :span="2">{{ detailData.remark || '无' }}</el-descriptions-item>
      </el-descriptions>
    </el-dialog>
  </div>
</template>

<script setup>
import {ref, onMounted} from 'vue'
import {useRouter} from 'vue-router'
import {ElMessage, ElMessageBox} from 'element-plus'
import {getAppointmentPage, reviewAppointment} from '@/api/appointment'
import {getEnabledTimeSlots} from '@/api/timeSlot'

const router = useRouter()

// 搜索表单
const searchForm = ref({
  visitorName: '',
  date: null,
  status: ''
})

// 表格数据
const loading = ref(false)
const tableData = ref([])
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)

// 时间段映射
const timeSlotMap = ref(new Map())

// 详情对话框相关
const detailDialogVisible = ref(false)
const detailData = ref({})

// 审核相关
const reviewDialogVisible = ref(false)
const currentRow = ref({})
const reviewForm = ref({
  status: 'CONFIRMED',
  remark: ''
})

// 获取预约列表
const fetchAppointments = async () => {
  loading.value = true
  try {
    // 处理日期范围
    const [startDate, endDate] = searchForm.value.date || [null, null]

    const params = {
      current: currentPage.value,
      size: pageSize.value,
      visitorName: searchForm.value.visitorName,
      status: searchForm.value.status,
      startDate: startDate ? startDate.format('YYYY-MM-DD') : undefined,
      endDate: endDate ? endDate.format('YYYY-MM-DD') : undefined
    }

    const res = await getAppointmentPage(params)
    tableData.value = res.records
    total.value = res.total
  } catch (error) {
    ElMessage.error('获取预约列表失败')
  } finally {
    loading.value = false
  }
}

// 获取时间段信息
const fetchTimeSlots = async () => {
  try {
    const response = await getEnabledTimeSlots()
      timeSlotMap.value = new Map(
        response.map(slot => [
          slot.id.toString(),
          `${slot.startTime} - ${slot.endTime}`
        ])
      )
  } catch (error) {
    ElMessage.error('获取时间段信息失败')
  }
}

// 状态相关方法
const getStatusType = (status) => {
  const types = {
    PENDING: 'warning',
    CONFIRMED: 'success',
    CANCELLED: 'info',
    REJECTED: 'danger'
  }
  return types[status] || 'info'
}

const getStatusText = (status) => {
  const texts = {
    PENDING: '待审核',
    CONFIRMED: '已确认',
    CANCELLED: '已取消',
    REJECTED: '已拒绝'
  }
  return texts[status] || status
}

// 搜索
const handleSearch = () => {
  currentPage.value = 1
  fetchAppointments()
}

// 重置搜索
const handleReset = () => {
  searchForm.value = {
    visitorName: '',
    date: null,
    status: ''
  }
  handleSearch()
}

// 审核
const handleReview = (row) => {
  currentRow.value = row
  reviewForm.value = {
    status: 'CONFIRMED',
    remark: ''
  }
  reviewDialogVisible.value = true
}

// 提交审核
const submitReview = async () => {
  if (reviewForm.value.status === 'REJECTED' && !reviewForm.value.remark) {
    ElMessage.warning('请输入拒绝原因')
    return
  }

  try {
    await reviewAppointment(
      currentRow.value.id,
      reviewForm.value.status,
      reviewForm.value.remark
    )
    ElMessage.success('审核完成')
    reviewDialogVisible.value = false
    fetchAppointments()
  } catch (error) {
    ElMessage.error('审核失败')
  }
}

// 查看详情
const handleDetail = (row) => {
  detailData.value = { ...row }
  detailDialogVisible.value = true
}

// 时间段设置
const handleTimeSlot = () => {
  router.push('/admin/appointment/time-slot')
}

// 分页
const handleSizeChange = (val) => {
  pageSize.value = val
  fetchAppointments()
}

const handleCurrentChange = (val) => {
  currentPage.value = val
  fetchAppointments()
}

// 在组件挂载时获取时间段数据
onMounted(() => {
  fetchTimeSlots()
  fetchAppointments()
})
</script>

<style scoped>
.appointment-container {
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.page-header h2 {
  margin: 0;
}

.search-card {
  margin-bottom: 20px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}
</style> 